package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysTopTitle;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysTopTitleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysTenantTitle;
import com.ruoyi.system.service.ISysTenantTitleService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 租户顶部选项卡Controller
 * 
 * @author kuaidou
 * @date 2021-08-31
 */
@Controller
@RequestMapping("/tenant/title")
public class SysTenantTitleController extends BaseController
{
    private String prefix = "system/tenant/title";

    @Autowired
    private ISysTenantTitleService sysTenantTitleService;

    @Autowired
    private ISysTopTitleService sysTopTitleService;

    @Autowired
    private ISysRoleService sysRoleService;

    @RequiresPermissions("tenant:title:view")
    @GetMapping()
    public String title()
    {
        return prefix + "/title";
    }

    /**
     * 查询租户顶部选项卡列表
     */
    @RequiresPermissions("tenant:title:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysTenantTitle sysTenantTitle)
    {
        startPage();
        List<SysTenantTitle> list = sysTenantTitleService.selectSysTenantTitleList(sysTenantTitle);
        // 获取平台选项卡
        SysTopTitle sysTopTitle = new SysTopTitle();
        sysTopTitle.setStatus(Constants.SUCCESS);
        List<SysTopTitle> sysTopTitles = sysTopTitleService.selectSysTopTitleList(sysTopTitle);
        if(CollectionUtils.isEmpty(list)){
            insertTenantTitle(sysTopTitles);
        }else {
            List<Long> titleIdList = list.stream().map(SysTenantTitle::getTitleId).collect(Collectors.toList());
            List<SysTopTitle> topTitles = sysTopTitles.stream().filter(title -> !titleIdList.contains(title.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(topTitles)){
                insertTenantTitle(topTitles);
            }
        }
        startPage();
        list = sysTenantTitleService.selectSysTenantTitleList(sysTenantTitle);
        return getDataTable(list);
    }

    private void insertTenantTitle(List<SysTopTitle> topTitles) {
        topTitles.forEach(topTitle->{
            SysTenantTitle tenantTitle = new SysTenantTitle();
            tenantTitle.setTitleId(topTitle.getId());
            tenantTitle.setTenantCode(ShiroUtils.getTenantCode());
            tenantTitle.setTargetTitle(topTitle.getTargetTitle());
            tenantTitle.setColour(topTitle.getColour());
            tenantTitle.setSort(topTitle.getSort());
            tenantTitle.setStatus(Constants.SUCCESS);
            tenantTitle.setTitleName(topTitle.getTitle());
            sysTenantTitleService.insertSysTenantTitle(tenantTitle);
        });
    }

    /**
     * 导出租户顶部选项卡列表
     */
    @RequiresPermissions("tenant:title:export")
    @Log(title = "租户顶部选项卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysTenantTitle sysTenantTitle)
    {
        List<SysTenantTitle> list = sysTenantTitleService.selectSysTenantTitleList(sysTenantTitle);
        ExcelUtil<SysTenantTitle> util = new ExcelUtil<SysTenantTitle>(SysTenantTitle.class);
        return util.exportExcel(list, "租户顶部选项卡数据");
    }

    /**
     * 新增租户顶部选项卡
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        modelMap.put("roles", sysRoleService.selectRoleAll());
        return prefix + "/add";
    }

    /**
     * 新增保存租户顶部选项卡
     */
    @RequiresPermissions("tenant:title:add")
    @Log(title = "租户顶部选项卡", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysTenantTitle sysTenantTitle, @RequestParam(name="roleIds",required = false) List<String> roleIds)
    {
        if(!CollectionUtils.isEmpty(roleIds)) {
            StringBuilder roleStr=new StringBuilder();
            for (String roleId : roleIds) {
                roleStr.append(roleId+",");
            }
            sysTenantTitle.setRoles(roleStr.toString());
        }
        sysTenantTitle.setTenantCode(ShiroUtils.getTenantCode());
        return toAjax(sysTenantTitleService.insertSysTenantTitle(sysTenantTitle));
    }

    /**
     * 修改租户顶部选项卡
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        mmap.put("roles", sysRoleService.selectRoleAll());
        SysTenantTitle sysTenantTitle = sysTenantTitleService.selectSysTenantTitleById(id);
        mmap.put("sysTenantTitle", sysTenantTitle);
        List<String> toleIds=new ArrayList();
        if(StringUtils.isNotEmpty(sysTenantTitle.getRoles())) {
            toleIds= Arrays.asList(sysTenantTitle.getRoles().split(","));
        }
        mmap.put("roleIds",toleIds);
        return prefix + "/edit";
    }

    /**
     * 修改保存租户顶部选项卡
     */
    @RequiresPermissions("tenant:title:edit")
    @Log(title = "租户顶部选项卡", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysTenantTitle sysTenantTitle, @RequestParam(name = "roleIds",required = false) List<String> roleIds)
    {
        if(!CollectionUtils.isEmpty(roleIds)) {
            StringBuilder roleStr=new StringBuilder();
            for (String roleId : roleIds) {
                roleStr.append(roleId+",");
            }
            sysTenantTitle.setRoles(roleStr.toString());
        }
        sysTenantTitle.setTenantCode(ShiroUtils.getTenantCode());
        return toAjax(sysTenantTitleService.updateSysTenantTitle(sysTenantTitle));
    }

    /**
     * 删除租户顶部选项卡
     */
    @RequiresPermissions("tenant:title:remove")
    @Log(title = "租户顶部选项卡", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysTenantTitleService.deleteSysTenantTitleByIds(ids));
    }

    /**
     * 状态修改
     */
    @Log(title = "租户顶部选项卡", businessType = BusinessType.UPDATE)
    @RequiresPermissions("tenant:title:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysTenantTitle title)
    {
        return toAjax(sysTenantTitleService.updateSysTenantTitle(title));
    }
}
